import * as Icon from "@ant-design/icons";
import React, { useState } from "react";
import { tabListType } from "./utils/types";
import { setMenu } from "@/store/modules/index";
import leftTabLess from "./index.module.less";

function LeftTab({ tabList = [], childrenSelectMenu, menu }: any) {
  // 用于存储当前选中的父菜单路径
  const [activeParent, setActiveParent] = useState<string | null>(null);

  // 用于创建图标元素的函数，首先判断 Icon 是否存在
  const iconToElement = (name: string) =>
    name
      ? React.createElement(Icon && (Icon as any)[name], {
          style: { fontSize: "14px" },
        })
      : null; // 如果没有 icon，则返回 null 不渲染图标

  // 点击菜单项时选择菜单
  const selectMenu = (item: tabListType) => {
    childrenSelectMenu(item);
  };

  // 递归查找父菜单路径
  const findParentPath = (items: tabListType[], childPath: string) => {
    for (const item of items) {
      if (item.Children && item.Children.length > 0) {
        if (item.Children.some((child) => child.Path === childPath)) {
          setActiveParent(item.Path);
          break;
        }
        // 继续递归查找
        findParentPath(item.Children, childPath);
      }
    }
  };

  // 递归渲染菜单项
  const renderMenuItems = (items: tabListType[]) => {
    return items.map((item: tabListType, index: number) => {
      const isParentActive = activeParent === item.Path;
      return (
        <div key={index}>
          <div
            className={[
              "tabs_items",
              menu === item.Path ? "tabs_items_active" : "",
              isParentActive ? "activeParent" : "",
            ].join(" ")}
            onClick={() => selectMenu(item)}
          >
            <div className="icon">{iconToElement(item.Icon)}</div>
            <div className="left_name">{item.Name}</div>
          </div>

          {/* 如果有子菜单，则递归渲染 */}
          {item.Children.length > 0 && (
            <div className={leftTabLess.sub_menu}>
              {renderMenuItems(item.Children)}
            </div>
          )}
        </div>
      );
    });
  };

  return (
    <>
      <div className={leftTabLess.tabs_all_content}>
        {renderMenuItems(tabList)}
      </div>
    </>
  );
}

export default LeftTab;
